<template lang='pug'>
  section.shopping-cart
    van-nav-bar(
      left-arrow
      title="购物车"
      @click-left="$router.back()"
      )
    empty(title="购物车空空如也，快去挑一件吧 😊" v-show="!isLoading && (!carts || !carts.length)")
    van-list(
      v-model="isLoading"
      :finished="finished"
      @load="onLoad"
      )
      van-checkbox-group(v-model="result" @change="select" )
        van-swipe-cell(:right-width="65" v-for="cart in carts" :on-close="onClose" :key="cart.id")
          van-checkbox(:name="cart" checked-color="rgba(232, 25, 15, 1)")
          van-card(
            :num="cart.quantity"
            tag="标签"
            :price="cart.price"
            :title="cart.name"
            :desc="cart.subtitle || ''"
            :thumb="cart.mainImage"
            )
            div(slot="footer")
              van-stepper(v-model="cart.quantity" :integer="true")
          .del(slot="right" @click="delCart([{id: cart.id}])") 删除

    van-submit-bar(
      :disabled="!result || !result.length"
      :price="total * 100"
      button-text="提交订单"
      @submit="buy"
      )
      van-checkbox(
        v-model="isSelectAll" 
        @change="selectAll" 
        checked-color="rgba(232, 25, 15, 1)" 
        @click.native="selectAllClick"
        ) 全选
            
    
</template>

<script type='text/ecmascript-6'>
  import { saveorder } from '~/assets/js/order'
  import empty from '~/components/empty'

  export default {
    components: {
      empty
    },
    data() {
      return {
        isLoading: false,
        finished: true,
        result: [],
        isSelectAll: false,
        num: 0,
        carts: []
      }
    },
    computed: {
      user() {
        return this.$store.state.authUser || {}
      },
      userId() {
        if (!this.user ||!this.user.user) return ''
        return this.user.user.id
      },
      total() {
        if (!this.result || !this.result.length) return 0
        return this.result.reduce((total, currentItem) => total + currentItem.price * currentItem.quantity, 0)
      },
    },
    asyncData({ store }) {
      // console.log(store.state, 8888888888888)
    },
    beforeMount() {
      this.getCart()
    },
    methods: {
      delCart(ids) {
        this.$dialog.confirm({
          title: '',
          message: '从购物车移除？'
        })
          .then(() => {
            this.$post('/api/platform/cart/delete', ids, 'JSON')
              .then(resp => {
                if (resp && resp.msg === 'ok') {
                  this.$toast.success('删除成功')
                  this.getCart()
                } else {
                  this.$toast.fail('删除失败')
                }
              })
              .catch(() => { this.$toast.fail('删除失败') })

          })
      },
      async getCart() {
        this.isLoading = true
        const resp = await this.$post('/api/platform/cart/cartPage', { userId: this.userId })
        this.isLoading = false
        console.log('userId', this.userId)
        console.log('cart', resp)
        this.carts = resp.data || []
      },
      onClose(clickPosition, instance) {
        console.log('1111111')
        instance.close()
      },
      toggle(index) {
        console.log(this.$refs.checkboxes[index].$el, '1111111')
        this.$refs.checkboxes[index].toggle();
      },
      onLoad() {},
      select(values) {
        // console.log('values', values)
        // console.log('result', this.result)
        const result = this.result || []
        this.isSelectAll = result.length === this.carts.length
      },
      buy() {
        // const { name: productName, price: currentUnitPrice, mainImage: productImage, subtitle: title } = this.commodity || {}
        console.log('result', this.result)
        const orders = this.result.map(item => ({
          productId: item.productId,
          productName: item.name, // 商品名 
          title: item.subtitle,
          currentUnitPrice: item.price, // 生成订单时的商品单价，单位是元,保留两位小数
          userId: this.userId,
          quantity: item.quantity, // 商品数量
          productImage: item.mainImage,
          totalPrice: item.quantity * item.price, // 商品总价
        }))
        saveorder(orders)
        this.$router.push({
          path: '/buy',
          query: { fromCart: true },
        })
      },
      selectAll(bol) {
        // const result = this.list.map((item, index) => index + 1)
        // this.result = bol ? this.carts : []
      },
      selectAllClick() {
        this.result = this.isSelectAll ? this.carts : []
      },
    }
  }
</script>

<style lang='stylus' rel='stylesheet/stylus'>

@import '~assets/stylus/variable.styl'

.shopping-cart
  .van-swipe-cell__wrapper
    display flex
    align-items center
    background-color #fafafa
    .van-checkbox
      flex 0 0 3rem
      text-align right
    .van-card
      flex 1
      .van-card__desc
        white-space normal
    .del
      margin-top 1rem
      background-color $color-black-bl
      width 65px
      color $color-white
      height calc(100% - 1rem)
      display inline-flex
      justify-content center
      align-items center
  .van-submit-bar
    .van-checkbox
      margin-left 1rem
</style>
